package com.intel.factorytest.activity;


import java.io.IOException;

import android.app.Activity;
import android.content.Intent;
import android.content.pm.ActivityInfo;
import android.content.res.Configuration;
import android.hardware.Camera;
import android.hardware.Camera.PictureCallback;
import android.hardware.Camera.ShutterCallback;
import android.os.Bundle;
import android.os.Handler;
import android.os.Message;
import android.util.Log;
import android.view.Gravity;
import android.view.Surface;
import android.view.SurfaceHolder;
import android.view.SurfaceView;
import android.view.View;
import android.view.ViewGroup.LayoutParams;
import android.view.WindowManager;
import android.widget.Button;
import android.widget.TextView;
import java.io.BufferedOutputStream;
import android.graphics.Bitmap;
import android.graphics.BitmapFactory;
import android.os.Environment;
import java.io.File;
import java.io.FileOutputStream;

import com.intel.factorytest.R;

public class CameraFrontTest extends BaseActivity implements SurfaceHolder.Callback,android.view.View.OnClickListener{
    private Button mSucBtn;
    private Button mFailBtn;
    
    private SurfaceView mCameraView = null;
    private Button mCaptureButton;
    private android.hardware.Camera mCameraDevice = null;
    private boolean beforePreview = true,isPreview = false, duringCapture = false,afterCapture=false;
    private boolean mIsFinish = false;
    SurfaceHolder holder;
    private TextView mcTestText;
    private static final int FONT_CAMERA = 1;
    private static final int BEFORE_FONT_CAMERA = 2;
    private int cameraId = 0;
    public void onCreate(Bundle b){
        super.onCreate(b);
        Log.i("ljr","onCreate() ");
        setContentView(R.layout.camera_whole_test);
        initView();
       
                this.getWindow().addFlags(WindowManager.LayoutParams.FLAG_TURN_SCREEN_ON);
        this.getWindow().addFlags(WindowManager.LayoutParams.FLAG_DISMISS_KEYGUARD);
        this.getWindow().addFlags(WindowManager.LayoutParams.FLAG_KEEP_SCREEN_ON);
        mCaptureButton = (Button)findViewById(R.id.camera_capture_btn);
        mCameraView = (SurfaceView)findViewById(R.id.cameraView);


        mcTestText = new TextView(this);
        mcTestText.setLayoutParams(new LayoutParams(LayoutParams.FILL_PARENT, LayoutParams.FILL_PARENT));
        mcTestText.setGravity(Gravity.CENTER);
        mcTestText.setTextSize(16);


        holder = mCameraView.getHolder();
        holder.addCallback(this);
        holder.setType(SurfaceHolder.SURFACE_TYPE_PUSH_BUFFERS);
        //set up listeners
        mCaptureButton.setOnClickListener(this);


    }
    
    protected void initView() {
        mSucBtn = (Button) findViewById(R.id.successbutton);
        mFailBtn = (Button) findViewById(R.id.failbutton);
        
        mSucBtn.setOnClickListener(new View.OnClickListener() {
            
            @Override
            public void onClick(View v) {
                // TODO Auto-generated method stub
                is_pass = true;
                finish();
            }
        });
        
        mFailBtn.setOnClickListener(new View.OnClickListener() {
            
            @Override
            public void onClick(View v) {
                // TODO Auto-generated method stub
                is_pass = false;
                finish();
            }
        });
    }

    public void onResume(){
        Log.i("ljr","onResume() ");
        super.onResume();
        openFontCamerawithholder();
    }
    
    public int getDisplayRotation(Activity activity) {
         int rotation = activity.getWindowManager().getDefaultDisplay()
             .getRotation(); 
         switch (rotation) {
             case Surface.ROTATION_0: return 0;
             case Surface.ROTATION_90: return 90;
             case Surface.ROTATION_180: return 180;
             case Surface.ROTATION_270: return 270;
         }
         return 0;
    }

   public int getDisplayOrientation(int degrees, int cameraId) {
         Camera.CameraInfo info = new Camera.CameraInfo();
         Camera.getCameraInfo(cameraId, info);
         int result;
         if (info.facing == Camera.CameraInfo.CAMERA_FACING_FRONT) {
             result = (info.orientation + degrees) % 360;
             result = (360 - result) % 360;
         Log.i("ljr", "info.orientation = " + info.orientation + "  degrees = " + degrees + " result = " + result);
         } else {
             result = (info.orientation - degrees + 360) % 360;
         Log.i("ljr", "info.orientation = " + info.orientation + "  degrees = " + degrees + " result = " + result);
         }
         return result;
     }


    private void openCamerawithholder() {
        mCameraView.setVisibility(View.GONE);
        if(2 == android.hardware.Camera.getNumberOfCameras()) {
            try {
                mCameraDevice = android.hardware.Camera.open(0);//for the big camera yjcui
                cameraId = 0;
            } catch(Exception e) {
                mcTestText.setText("The back camera is not available");
                setContentView(mcTestText);
            }
        } else if(1 == android.hardware.Camera.getNumberOfCameras()) {
            android.hardware.Camera.CameraInfo cameraInfo = new android.hardware.Camera.CameraInfo();
            android.hardware.Camera.getCameraInfo(0, cameraInfo);
            if(android.hardware.Camera.CameraInfo.CAMERA_FACING_BACK == cameraInfo.facing) {
                try {
                    mCameraDevice = android.hardware.Camera.open(0);//for the big camera yjcui
                    cameraId = 0;
                } catch(Exception e) {
                    mcTestText.setText("The back camera is not available");
                    setContentView(mcTestText);
                }
            } else {
                mcTestText.setText("The back camera is not available");
                setContentView(mcTestText);
                mItemTestFinish = true;
            }
        } else {//not available camera
            mcTestText.setText("Not available camera");
            setContentView(mcTestText);
            mItemTestFinish = true;
        }

        android.os.SystemProperties.set("service.camera.id", "1");
        try {
            
            if(mCameraDevice != null) {
                mCameraDevice.setPreviewDisplay(holder);
            }
            mCameraView.setVisibility(View.VISIBLE);
        } catch (IOException e) {
            // TODO Auto-generated catch block
            e.printStackTrace();
        }
        beforePreview = false;
        isPreview = true;
        if(isPreview){
            if(mCameraDevice != null) {
                mCameraDevice.startPreview();
                mCameraDevice.setDisplayOrientation(getDisplayOrientation(getDisplayRotation(this), cameraId));
            }
        }
        
        setButtonState();

    }
    private void openFontCamerawithholder() {
        mCameraView.setVisibility(View.GONE);
        if(2 == android.hardware.Camera.getNumberOfCameras()) {
            try {
                mCameraDevice = android.hardware.Camera.open(1);//for the small camera yjcui
                cameraId = 1;
            } catch(Exception e) {
                mcTestText.setText("The front camera is not available");
                setContentView(mcTestText);
            }
            
        } else if(1 == android.hardware.Camera.getNumberOfCameras()) {
            android.hardware.Camera.CameraInfo cameraInfo = new android.hardware.Camera.CameraInfo();
            android.hardware.Camera.getCameraInfo(0, cameraInfo);
            if(android.hardware.Camera.CameraInfo.CAMERA_FACING_FRONT  == cameraInfo.facing) {
                try {
                    mCameraDevice = android.hardware.Camera.open(0);//for the small camera yjcui
                    cameraId = 0;
                } catch(Exception e) {
                    mcTestText.setText("The front camera is not available");
                    setContentView(mcTestText);
                }
            } else {
                mcTestText.setText("The front camera is not available");
                setContentView(mcTestText);
                mItemTestFinish = true;
            }
        } else {//not available camera
            mcTestText.setText("Not available camera");
            setContentView(mcTestText);
            mItemTestFinish = true;
        }
        try {
            if(mCameraDevice != null) {
                mCameraDevice.setPreviewDisplay(holder);
            }
            mCameraView.setVisibility(View.VISIBLE);
        } catch (IOException e) {
            // TODO Auto-generated catch block
            e.printStackTrace();
        }
        beforePreview = false;
        isPreview = true;
        if(isPreview){
            if(mCameraDevice != null) {
                mCameraDevice.startPreview();
                mCameraDevice.setDisplayOrientation(getDisplayOrientation(getDisplayRotation(this), cameraId));
            }
            
        }
        setButtonState();

    }

    Handler mHandler = new Handler(){
        @Override
        public void handleMessage(Message msg) {
            if(msg.what==FONT_CAMERA){
                resetStates();
                isPreview = true;
                beforePreview = true;
                //openFontCamerawithholder();
                mIsFinish = true;
                showResultButton();

            } else if(msg.what== BEFORE_FONT_CAMERA){
                if(mCameraDevice != null){
                    if(isPreview){
                        mCameraDevice.stopPreview();
                    }
                    mCameraDevice.release();
                    mCameraDevice = null;
                
                }
                if(mIsFinish) {
//                    finish();
                    showResultButton();
                } else {
                    sendEmptyMessageDelayed(FONT_CAMERA, 500);
                }
                

            }

        }
        
    };
    
    private void showResultButton() {
        mSucBtn.setVisibility(View.VISIBLE);
        //mFailBtn.setVisibility(View.VISIBLE);
        mCaptureButton.setVisibility(View.INVISIBLE);
        mItemTestFinish = true;//add by wangsm
    }

    @Override
    public void onConfigurationChanged(Configuration newConfig) {
        super.onConfigurationChanged(newConfig);
        Log.i("ljr","onConfigurationChanged ");
        if(isPreview && mCameraDevice != null) {
            mCameraDevice.setDisplayOrientation(getDisplayOrientation(getDisplayRotation(this), cameraId));
        }
    }

    public void onPause(){
        super.onPause();
        Log.i("ljr","onPause() ");
        if(mCameraDevice != null){
            if(isPreview){
                mCameraDevice.stopPreview();
            }
            mCameraDevice.release();
            mCameraDevice = null;
        }
        android.os.SystemProperties.set("service.camera.id", "0");
    }
    public void onDestroy(){
        super.onDestroy();
        Log.i("ljr","onDestroy ");

    }


    private void setButtonState(){
        mCaptureButton.setEnabled(true);
        if(beforePreview){
            mCaptureButton.setEnabled(false);
        }else if(isPreview){
            mCaptureButton.setEnabled(true);
        }else if(duringCapture){
            mCaptureButton.setEnabled(false);
        }else if(afterCapture){
            mCaptureButton.setEnabled(false);
        }

    }

    private void resetStates(){
        beforePreview = false;
        isPreview = false;
        afterCapture=false;
        duringCapture = false;
    }
    public void surfaceChanged(SurfaceHolder holder, int format, int width,
            int height) {
        Log.i("ljr","surfaceChanged width="+width+" height="+height);

        try {
            if(mCameraDevice != null) {
                mCameraDevice.setPreviewDisplay(holder);
            }
        } catch (IOException e) {
            // TODO Auto-generated catch block
            e.printStackTrace();
        }

    }
    public void surfaceCreated(SurfaceHolder holder) {
        // TODO Auto-generated method stub
        Log.i("ljr","surfaceCreated ");
        //mCameraDevice = android.hardware.Camera.open(0);//for the big camera ljrui
    }
    public void surfaceDestroyed(SurfaceHolder holder) {
        Log.i("ljr","surfaceDestroyed ");

    }

    public void onClick(View v) {
        switch(v.getId()){
            case R.id.camera_capture_btn:
                resetStates();
                duringCapture = true;
                setButtonState();
                doCapture();
                isPreview = true;
                //mHandler.sendEmptyMessageDelayed(BEFORE_FONT_CAMERA, 500);
                mHandler.sendEmptyMessageDelayed(FONT_CAMERA, 500);
                break;
        }

    }

    private static String save_path = Environment.getExternalStorageDirectory().toString() + "/Pictures";
    private Bitmap mBitmap = null;

    private void doCapture(){
        
        Log.i("ljr","doCapture  mShutter = " + mShutter + ", mRaw = " + mRaw + ", mPostview = " + mPostview + ", mJpeg = " + mJpeg);
        mCameraDevice.takePicture(mShutter, mRaw, mPostview,mJpeg);
    }
    private ShutterCallback mShutter = new ShutterCallback(){

        public void onShutter() {
            Log.i("ljr","onShutter ");
        }
    };
    private PictureCallback mRaw = new PictureCallback() {

        public void onPictureTaken(byte[] data, android.hardware.Camera camera) {
            Log.i("ljr","mRaw "+(data==null?"has no data":"has data") + " camera="+camera.getParameters());
        }
    };
    private PictureCallback mPostview = new PictureCallback() {

        public void onPictureTaken(byte[] data, android.hardware.Camera camera) {
            Log.i("ljr","mPostview "+data.length);
        }
    };
    
    private PictureCallback mJpeg = new PictureCallback() {

        public void onPictureTaken(byte[] data, android.hardware.Camera camera) {
            Log.i("ljr","mJpeg ");
            resetStates();
            afterCapture = true;
            setButtonState();
            //save
            Log.i("ljr","mJpeg "+data.length);
            mBitmap = BitmapFactory.decodeByteArray(data, 0, data.length);
            File file = new File(save_path+"/front_camera.jpg");
            try {
                file.createNewFile();
                BufferedOutputStream os = new BufferedOutputStream(new FileOutputStream(file));
                mBitmap.compress(Bitmap.CompressFormat.JPEG, 100, os);
                os.flush();
                os.close();
            } catch (IOException e) {
            // TODO Auto-generated catch block
            e.printStackTrace();
            }
        }
    };

    @Override
        public void finish() {
            //tc.setTestResult(is_pass);
            super.finish();
        }
}

